package com.coderising.kailuncen;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cenkailun
 * @Date 17/4/16
 * @Time 上午11:33
 */
public class ReflectionUtil {

	public static void invokeSetMethods(Object o, Map<String, String> params) {
		List<Method> setMethods = fetchSetMethods(o);

		for (String fieldName : params.keySet()) {
			String setMethodName = buildMethodName(fieldName, "set");
			for (Method method : setMethods) {
				if (setMethodName.equalsIgnoreCase(method.getName())) {
					try {
						method.invoke(o, params.get(fieldName));
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	private static List<Method> fetchGetMethods(Object o) {
		List<Method> getMethods = new ArrayList<>();
		Method[] declaredMethods = o.getClass().getDeclaredMethods();
		for (Method method : declaredMethods) {
			if (method.getName().startsWith("get"))
				getMethods.add(method);
		}
		return getMethods;
	}

	private static String buildMethodName(String fieldName, String prefix) {
		return prefix + fieldName;
	}

	private static List<Method> fetchSetMethods(Object o) {
		List<Method> setMethods = new ArrayList<>();
		Method[] declaredMethods = o.getClass().getDeclaredMethods();
		for (Method method : declaredMethods) {
			if (method.getName().startsWith("set"))
				setMethods.add(method);
		}
		return setMethods;
	}

	public static Map<String, Object> invokeGetMethods (Object o) {
        Map<String, Object> params = new HashMap<>();
        List<Method> getMethods = fetchGetMethods(o);
        for (Method method : getMethods) {
            String fieldName = method.getName().replaceFirst("get","").toLowerCase();
            try {
                params.put(fieldName,method.invoke(o));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return params;
    }
}
